import {Component, OnInit} from '@angular/core';
import {Ds} from '../ds';
import {MsgConstants} from '../../../../constants/constants';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {ResponseUtil} from '../../../../util/response-util';
import {PageSubject} from '../../../../util/page-subject';
import {OneDialogService} from '../../../../widgets/one-dialog/one-dialog.service';
import {DsService} from '../ds.service';
import {Path} from '../../../../portal/admin/admin-breadcrumb/breadcrumb';
import {MsgResult} from '../../../../models/msg-result';
import {DataDictionaryService} from "../../../../services/dataDictionary.service";

@Component({
  selector: 'app-ds-update',
  templateUrl: './ds-update.component.html',
  styleUrls: ['./ds-update.component.css']
})
export class DsUpdateComponent implements OnInit {

  // 声明实例
  ds: Ds;

  dsId: string;

  useTypes: Array<any> = [];

  dsForm: FormGroup;
  /**
   * 校验字段
   * @type {{name: string; ip: string; port: string}}
   */
  formErrors = {
    'dsName': '',
    'dbName': '',
    'dbType':'',
    'useType':'',
    'ip': '',
    'port': '',
    'userName': '',
    'passWord': '',
  };
  validationMessages = {

    'dsName': {
      'required': '数据源名称不能为空',
      'pattern' : '输入汉字或数字',
      'maxlength':'长度不能超过30'
    },
    'dbName': {
      'required': '实例名称不能为空',
      'pattern' : '输入字母，数字或"_"',
      'maxlength':'长度不能超过30'
    },
    'useType': {
      'required': '使用类型不能为空'
    },
    'dbType': {
      'required': '数据库类型不能为空'
    },
    'ip': {
      'required': '数据源IP不能为空',
      'pattern' : '请输入正确的ip格式 ',
    },
    'port': {
      'required': '端口不能为空',
      'pattern' : '请输入正确的端口格式 ',
    },
    'userName': {
      'required': '用户名不能为空',
      'pattern' : '输入字母，数字或"_" ',
      'maxlength':'长度不能超过16'
    },
    'passWord': {
      'required': '密码不能为空',
      'maxlength':'长度不能超过20'
    },

  }






  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private responseUtil: ResponseUtil,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private dsService: DsService,
    private dataDictionaryService: DataDictionaryService,
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.initDataDictionary();
    if (!!this.route.snapshot.params['id']) {
      this.dsId = this.route.snapshot.params['id'];
      this.initDsUpdateForm(this.dsId);
    }
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    const path = new Path ('审核系统', '');
    this.pageSubject.pushPage('数据源管理', '修改', path);
  }


  /**
   * 初始化数据字典数据
   */
  initDataDictionary(){
    this.useTypes = [];
    this.dataDictionaryService.getChildDicByCode('DSSYLX').subscribe(
      result => this.responseUtil.success(result ,this.processDictionaryResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   * 处理查询结果
   * @param result
   */
  private processDictionaryResult =(result :MsgResult)=>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        result.data.forEach((val) => {
          this.useTypes.push({
            name: val.display,
            value: val.value,
          })
        })
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  /**
   * 构造表单
   */
  buildForm(): void {
    this.dsForm = this.fb.group({
      'id': [this.ds.id],
      'dsName': [this.ds.dsName, [
        Validators.required,
        Validators.pattern(/^[\u4e00-\u9fa50-9A-Za-z]+$/),
        Validators.maxLength(30),
      ]],
      'dbName': [this.ds.dbName, [
        Validators.required,
        Validators.pattern(/^[A-Za-z0-9_.]+$/),
        Validators.maxLength(30),
      ]],
      'dbType': [this.ds.dbType, [
        Validators.required,
      ]],
      'useType': [this.ds.useType, [
        Validators.required,
      ]],
      'ip': [this.ds.ip, [
        Validators.required,
        Validators.pattern(/^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])(\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)){3}$/),
      ]],
      'port': [this.ds.port, [
        Validators.required,
        Validators.pattern(/^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/),
      ]],
      'userName': [this.ds.userName,[
        Validators.required,
        Validators.pattern(/^[A-Za-z_0-9]+$/),
        Validators.maxLength(16),
      ]],
      'passWord': [this.ds.passWord,[
        Validators.required,
        Validators.maxLength(20),
      ]],
      'isUse': ['1'],
    });

    this.dsForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }
  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.dsForm) {
      return;
    }
    const form = this.dsForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 初始化表单
   */

  private initDsUpdateForm(dsId) {
    // 获取路由参数
    const id = this.route.snapshot.params['id']
    this.dsService.getDataSourceByID(id).subscribe(
      result => this.responseUtil.success(result, this.generateDsUpdateById),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *
   * @param {MsgResult} result
   */
  private generateDsUpdateById = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.ds = result.data;
      // this.ds.dsName = result.data.dsName;
      this.dsForm.patchValue(this.ds);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }


  /**
   *实现修改功能
   */
    onSubmit() {
    // 获取表单信息
    this.ds = this.dsForm.value;
    this.dsService.updateDataSource(this.ds).subscribe(
      result => this.responseUtil.success(result, this.processDsUpdateResult),
      message => this.responseUtil.error(message)
    )
  }

  private processDsUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancelDsUpdate());
      // this.dialogService.successWithCancelBtn('修改成功，是否继续添加？', () => this.initObject(), () => this.cancelDsUpdate());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }  }

  /**
   * 取消修改
   */
  cancelDsUpdate() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.ds = new Ds('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
    this.buildForm();
  }




}
